import { RouteLocationNormalizedLoaded, useRoute, useRouter } from 'vue-router';
import { onMounted, reactive, ref, watch } from 'vue';
const home = {
    title: '仪表盘',
    fullPath: '/',
    closable: false,
    loading: false
}
export interface Page {
    title: string;
    fullPath: string,
    closable: boolean,
    loading: boolean;
}

const route2Page = (route: RouteLocationNormalizedLoaded): Page => {

    if (typeof route.name != 'string') {
        throw new Error("route name must be string");
    }

    return {
        title: route.meta.title ? <string>route.meta.title : <string>route.name,
        fullPath: route.fullPath,
        closable: true,
        loading: false,
    };
};
export function useMultiTab() {
    const router = useRouter();
    const route = useRoute();
    const items = reactive([home]);
    const activeKey = ref(route.fullPath);

    const add = (route: RouteLocationNormalizedLoaded) => {
        const page = route2Page(route);
        if (items.find(p => p.fullPath == route.fullPath) == undefined) {
            items.push(page);
        }
        activeKey.value = page.fullPath;
    };

    const removeAll = () => {
        if (home != undefined) {
            router.push(home.fullPath).then(() => {
                activeKey.value = home.fullPath;
            });
            items.splice(0, items.length, home);
        } else {
            items.splice(0, items.length);
        }
    };

    const remove = (key: string) => {
        if (items.length == 1) {
            return;
        }
        const index = items.findIndex(page => page.fullPath == key);
        if (index == -1) {
            return;
        }

        items.splice(index, 1);
        if (key == route.fullPath) {
            const key = items[items.length - 1].fullPath;
            router.push(key).then(() => {
                activeKey.value = key;
            });
        }
    };


    const active = (key: string) => {
        const page = items.find(p => p.fullPath == key);
        if (page != undefined) {
            router.push(page.fullPath);
        }
    };

    watch(() => route.fullPath, (current) => {
        console.log(current)
        if (current != undefined && current != activeKey.value && current != '') {
            add(route);
        }
    });

    onMounted(() => {
        //Add current page
        add(route);
    })

    return {
        activeKey,
        remove,
        active,
        items,
        removeAll
    };
}
